<template>
    <div class="d-flex justify-content-center mb-5">
        <el-row class="main_opt">
            <el-col :span="8">
                <el-tree :props="props" :load="loadNode" lazy @node-click="nodeClick"/>
            </el-col>
            <el-col :span="16">
                <MyForm ref="formRef" :form="editForm" :rules="rules" labelWidth="120px">
                    <el-form-item label="字典编码" prop="code">
                        <el-input v-model="editForm.code"/>
                    </el-form-item>
                    <el-form-item label="字典编码名称" prop="codeName">
                        <el-input v-model="editForm.codeName" />
                    </el-form-item>
                    <el-form-item label="字典值" prop="value">
                        <template v-if="isPreview" style="align-items: inherit;">
                            <el-input v-model="editForm.value" disabled class="pb-3"/>
                            <el-row>
                                <el-col :sapn="24">
                                    <!-- 文件预览 -->
                                    <FilePreview :fileUrl="editForm.value"/>
                                </el-col>
                                <el-col :sapn="24" class="pt-4">
                                    <!-- 上传文件 -->
                                    <FileUpload
                                        :methond = "'coveringFile'"
                                        :methondName = "'覆盖'"
                                        :acceptedExtensions = "['docx']"
                                        @coveringFile = "coveringFile"
                                    />
                                </el-col>
                            </el-row>
                        </template>
                        <el-input v-else v-model="editForm.value" type="textarea" :rows="20"/>
                    </el-form-item>
                    <el-form-item label="创建时间" prop="createdTime">
                        <el-input v-model="editForm.createdTime" disabled/>
                    </el-form-item>
                    <el-form-item label="创建人" prop="createdBy"> 
                        <el-input v-model="editForm.createdBy" disabled/>
                    </el-form-item>
                    <el-form-item label="修改时间" prop="updatedTime">
                        <el-input v-model="editForm.updatedTime" disabled/>
                    </el-form-item>
                    <el-form-item label="修改人" prop="updatedBy">
                        <el-input v-model="editForm.updatedBy" disabled/>
                    </el-form-item>
                    <el-form-item class="text-right">
                        <el-button type="primary" @click="update">修改</el-button>
                    </el-form-item>
                </MyForm>
            </el-col>
        </el-row>
    </div>
</template>
<script lang="ts" setup>
    import { reactive, inject, computed,ref } from 'vue'
    import { ElMessage } from 'element-plus'
    import type { FormInstance, FormRules } from 'element-plus'
    import type Node from 'element-plus/es/components/tree/src/model/node'
    import FilePreview from '@/components/FilePreviewDialog.vue'
    import FileUpload from '@/components/FileUpload.vue'
    import MyForm from '@/components/MyForm.vue'
    import { GetDataDictionaryTypes, UpdateConfig, CoveringFile } from "@/api/common/dataDictionary.js"
    import moment from 'moment'

    /**
     * form表单引用
     */
    const formRef = ref()
    /**
     * docx文件预览引用
     */
    const refWord = ref(null)
    /**
     * 修改表单
     */
    const editForm = ref({})

    const data = reactive({
        previewUrl: ''
    })
    /**
     * 节点树接口
     */
    interface Tree {
        codeName: string
        leaf?: boolean
    }
    /**
     * 节点树属性
     */
    const props = {
        label: 'codeName',
        children: 'zones',
        isLeaf: 'leaf',
    }
    /**
     * 加载节点
     */
    const loadNode = (node: Node, resolve: (data: Tree[]) => void) => {
        // 根节点
        if (node.level === 0) {
            GetDataDictionaryTypes("ROOT")
            .then((response) => {
                response.data.content.forEach(element => {
                    element.createdTime = moment(element.createdTime).format('YYYY-MM-DD HH:mm:ss')
                    element.updatedTime = moment(element.updatedTime).format('YYYY-MM-DD HH:mm:ss')
                });
                return resolve(response.data.content)
            });
        } else {// 字节点
            GetDataDictionaryTypes(node.data.code)
            .then((response) => {
                if(response.data.content.length > 0) {
                    response.data.content.forEach(element => {
                        element.createdTime = moment(element.createdTime).format('YYYY-MM-DD HH:mm:ss')
                        element.updatedTime = moment(element.updatedTime).format('YYYY-MM-DD HH:mm:ss')
                    });
                    return resolve(response.data.content)
                }
                return resolve([])
            });
        }
    }
    /**
     * 节点点击事件处理
     */
    const nodeClick = (node) => {
        editForm.value = node
    }
    // 
    /**
     * 修改配置
     */
    const update = () => {
        if(!editForm.value.id) {
            ElMessage.error('字典修改内容为空，请输入要修改的内容')
            return false
        }
        formRef.value.checkParam()
            .then((res) => {
                UpdateConfig(editForm.value)
                    .then((response) => {
                        ElMessage({
                            message: '修改字典成功！',
                            type: 'success',
                        })
                        // 刷新当前页面
                        reload()
                    }).catch((error) => {});
            })
            .catch((err) => {})
    }
    /**
     * 调用 App.vue 提供的方法，进行刷新
     */
    const reload = inject("reload")
    /**
     * 覆盖配置中文件
     */
    const coveringFile =(fileList) => {
        if (fileList.length === 0) {
            return ElMessage.error('请选择要上传的文件');
        }
        const formData = new FormData();
        formData.append('id', editForm.value.id)
        fileList.forEach((file) => {
            formData.append('file', file.raw);
        });
        CoveringFile(formData)
            .then((response) => {
                 ElMessage({
                    message: '文件覆盖成功！',
                    type: 'success',
                })
                // 刷新当前页面
                reload()
            }).catch((error) => {});
    }   
    /**
     * 计算属性，字典值是否预览
     */
    const isPreview = computed(() => {
       if(editForm.value.value) {
            let pos = editForm.value.value.lastIndexOf(".");
            let lastName = editForm.value.value.substring(pos+1, editForm.value.value.length);
            if(lastName == "docx") {
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    })
     /**
     * 表单检验规则
     */
     const rules = reactive<FormRules<RuleForm>>({
        code: [
            {required:true, message:'字典编码不能为空', trigger:'blur'}
        ],
        codeName: [
            {required:true, message:'字典编码名称不能为空', trigger:'blur'}
        ]
    })
</script>
<style scoped>
    .main_opt {
        width: 70%;
    }
</style>